package info.techgeek.labs.java5Features.thread.arv;
/*
import info.techgeek.dis.dao.ICMDBAccessDAO;
import info.techgeek.dis.helper.JiraEventListenerProperties;
import info.techgeek.dis.view.ListenerView;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.atlassian.jira.ComponentManager;
import com.atlassian.jira.ManagerFactory;
import com.atlassian.jira.config.ConstantsManager;
import com.atlassian.jira.exception.CreateException;
import com.atlassian.jira.exception.RemoveException;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.issue.MutableIssue;
import com.atlassian.jira.issue.link.IssueLink;
import com.atlassian.jira.issue.link.IssueLinkManager;
import com.atlassian.jira.issue.link.LinkCollection;
import com.atlassian.jira.util.ErrorCollection;
import com.atlassian.jira.util.JiraUtils;
import com.atlassian.jira.workflow.JiraWorkflow;
import com.atlassian.jira.workflow.WorkflowException;
import com.atlassian.jira.workflow.WorkflowManager;
import com.atlassian.jira.workflow.WorkflowTransitionUtil;
import com.atlassian.jira.workflow.WorkflowTransitionUtilImpl;
import com.opensymphony.workflow.loader.ActionDescriptor;
import com.opensymphony.workflow.loader.StepDescriptor;
import com.opensymphony.workflow.loader.WorkflowDescriptor;

/**
 * Task ThreadPool Executer Execute when task is Create from
 * Confluence,CRQToTask,also For Normal Task workflow it create link with CRQ
 * also it remove link Check status also change the status
 * 
 * @author techgeek
 * 
 */
/*
public class TaskThreadPoolReader implements Runnable {
	private static final Logger log = Logger
			.getLogger(TaskThreadPoolReader.class);
	private static final JiraEventListenerProperties RESOURCEBUNDLE = new JiraEventListenerProperties();

	ListenerView listenerView;
	ComponentManager componentManager = ComponentManager.getInstance();
	IssueLinkManager issueLinkManager = componentManager.getIssueLinkManager();

	public ListenerView getListenerView() {
		return listenerView;
	}

	public void setListenerView(ListenerView listenerView) {
		this.listenerView = listenerView;
	}

	public void run() {
		log.warn("******************************");
		log.warn("*                            *");
		log.warn("*  TaskThreadPoolReader      *");
		log.warn("*                            *");
		log.warn("******************************");

		// get Operation Type whether its going to insert or Update
		String operationType = listenerView.getOperationType();
		RESOURCEBUNDLE.readPropertyFile();
		ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
				new String[] { "JMSReceiver.Spring.cfg.xml" });

		ICMDBAccessDAO icmdbAccessDAO = (ICMDBAccessDAO) appContext
				.getBean("CMDBAccessDAO");

		// It gets the Task Id and Check whether already Link is available if
		// link is there it set that issue Key in View
		MutableIssue taskIssue = ManagerFactory.getIssueManager()
				.getIssueObject(listenerView.getJiraTaskId());
		LinkCollection linkCollection = issueLinkManager.getLinkCollection(
				taskIssue.getGenericValue(), listenerView.getRemoteUser());
		for (Issue crqIssue : (Collection<Issue>) linkCollection
				.getAllIssues()) {
			listenerView.setCrqIssueKeyOldValue(crqIssue.getKey());
		}
		// This Block will call only when Task is Updated and CrqIssuekeyOld
		// Value is not equal to new Value to delink
		log.warn("CMDBInsertUpdateThreadPoolReader:: Crq Issue Key Is"
				+ listenerView.getCrqissueKey());
		if ((listenerView.getCrqissueKey() == null && "".equals(listenerView
				.getCrqissueKey()))
				|| (2 == listenerView.getEventTypeId()
						&& listenerView.getCrqIssueKeyOldValue() != null && (!listenerView
						.getCrqIssueKeyOldValue().equals(
								listenerView.getCrqissueKey())))) {
			this.removeIssueLink();
			this.checkTransitionStatus(listenerView.getCrqIssueKeyOldValue());
		}
		// It check whether Crq Custom Field Already have Value Or not if its
		// having value it calls Create Issue Link and Check Issue Status
		if (listenerView.getCrqissueKey() != null
				&& !"".equals(listenerView.getCrqissueKey())) {
			this.createIssueLink();
			this.checkTaskStatus(listenerView.getCrqissueKey());
		}

		
	}

	/**
	 * It Create Issue Link when CRQ Custom Field Selected with Value
	 */

/*
	private void createIssueLink() {
		log.warn("CRQ Issue Key createIssueLink is"
				+ listenerView.getCrqissueKey());
		MutableIssue linkedIssue = ManagerFactory.getIssueManager()
				.getIssueObject(listenerView.getCrqissueKey());

		try {
			log.warn("Id createIssueLink is" + linkedIssue);
			log.warn("TaskIssueId createIssueLink is"
					+ listenerView.getTaskIssueId());
			log.warn(" RemoteUser createIssueLink is"
					+ listenerView.getRemoteUser());

			issueLinkManager.createIssueLink(listenerView.getTaskIssueId(),
					linkedIssue.getId(), 10010l, 1l, listenerView
							.getRemoteUser());
		} catch (CreateException e) {
			log.debug("Failed Create Issue Link :::" + e);
		}

	}

	/**
	 * It remove the link when CRQ Custom Field Modified or No value Selected
	 * when Edit the Task
	 */
/*
	private void removeIssueLink() {
		MutableIssue linkedIssue = ManagerFactory.getIssueManager()
				.getIssueObject(listenerView.getCrqIssueKeyOldValue());
		IssueLink issueLink = issueLinkManager.getIssueLink(listenerView
				.getTaskIssueId(), linkedIssue.getId(), 10010l);
		try {
			issueLinkManager.removeIssueLink(issueLink, listenerView
					.getRemoteUser());
		} catch (RemoveException e) {
			log.debug("Failed Remove Issue Link :::" + e);

		}
		log.warn("Issue Links are Removed");
	}

	/**
	 * Parent issue status updation depends upon the Child Issue Status for
	 * detail information about updation please refer Issue ALM-270
	 */
/*
	private void checkTaskStatus(String issueKey) {
		JiraEventListenerProperties listenerProperties = new JiraEventListenerProperties();
		listenerProperties.readPropertyFile();
		/*
		 * Following if block is added for parent issue status updation to
		 * Resolved or Validation In Progress based on child issue states with
		 * reference to the Task ALM-270
		 */
/*
		log.warn("Listner issue status is inside checkIssueStatus"
				+ listenerView.getStatus() + "Condition"
				+ "Task Cancelled".equals(listenerView.getStatus()));
		if ("Task Closed".equals(listenerView.getStatus())
				|| "Task Cancelled".equals(listenerView.getStatus())
				|| "Closed".equals(listenerView.getStatus())
				|| "Cancelled".equals(listenerView.getStatus())) {
			checkTransitionStatus(issueKey);

		}

	}

	/**
	 * This Progress Work Flow used to Change The Parent issue Status Depends
	 * upon the target Transition name
	 * 
	 * @param issueKey
	 * @param transitionName
	 */
/*
	private void progressWorkflow(String issueKey, String transitionName) {
		log.warn("progressWorkflow");
		try {
			final WorkflowManager workflowManager = ComponentManager
					.getInstance().getWorkflowManager();
			final WorkflowTransitionUtil transitionUtil = (WorkflowTransitionUtil) JiraUtils
					.loadComponent(WorkflowTransitionUtilImpl.class);
			MutableIssue mutableIssue = ManagerFactory.getIssueManager()
					.getIssueObject(issueKey);
			JiraWorkflow jiraWorkflow = workflowManager
					.getWorkflow(mutableIssue);
			WorkflowDescriptor descriptor = jiraWorkflow
					.getDescriptor();
			for (StepDescriptor stepDescriptor : (List<StepDescriptor>) descriptor
					.getSteps()) {
				if (stepDescriptor.getName().equals(
						RESOURCEBUNDLE.implentationProgress)) {
					boolean bFound = false;
					for (ActionDescriptor actionDescriptor : (List<ActionDescriptor>) stepDescriptor
							.getActions()) {
						log
								.warn("progressWorkflow :: inside Actiom targetTransitionName "
										+ transitionName);
						if (actionDescriptor.getName().equals(
								transitionName)) {
							mutableIssue.setAssignee(listenerView
									.getRemoteUser());
							transitionUtil.setIssue(mutableIssue);
							transitionUtil.setUsername(listenerView
									.getRemoteUser().getName());
							transitionUtil.setAction(actionDescriptor
									.getId());
							ErrorCollection errorCollection = transitionUtil
									.validate();
							printAnyErrors(mutableIssue, errorCollection);
							transitionUtil.progress();
							bFound = true;
							break;
						}
					}
					if (!bFound) {
						log.error("Could not find worflow transition for '"
								+ mutableIssue.getKey() + "' for step name '"
								+ RESOURCEBUNDLE.implentationProgress
								+ "' and transition '"
								+ RESOURCEBUNDLE.transitionCancel + "||"
								+ RESOURCEBUNDLE.transitonResolve + "'.");
					} else {
						break;
					}
				}
			}
		} catch (WorkflowException workflowException) {
			log.error("WorkFlowException" + workflowException);

		}
	}

	/**
	 * If any Error occurs in Progress Work Flow this methosd is Called to print
	 * the Errors
	 * 
	 * @param ParentIssue
	 * @param errorCollection
	 */
/*
	private void printAnyErrors(Issue ParentIssue,
			ErrorCollection errorCollection) {
		if (errorCollection.hasAnyErrors()) {
			log.warn("Field validation error auto-transitioning Parent Issue "
					+ ParentIssue.getKey() + ":");
			Iterator iter = errorCollection.getErrorMessages().iterator();
			while (iter.hasNext()) {
				String errMsg = (String) iter.next();
				log.warn("\t" + errMsg);
			}
			iter = errorCollection.getErrors().keySet().iterator();
			while (iter.hasNext()) {
				String fieldName = (String) iter.next();
				log.warn("\tField " + fieldName + ": "
						+ errorCollection.getErrors().get(fieldName));
			}
		}

	}

	private void checkTransitionStatus(String crqIssueKey) {
		try {
			boolean isAnyNonClosedAndNonCancelledStatus = false;
			log.warn("checkIssueStatus inside Cancelled Close");
			int closedStatusIssues = 0;
			int cancelledStatusIssues = 0;
			String targetTransitionName = null;
			// Its To Check All the Child Issue Status
			ComponentManager componentManager = ComponentManager.getInstance();
			IssueLinkManager issueLinkManager = componentManager
					.getIssueLinkManager();
			MutableIssue mutableIssue = ManagerFactory.getIssueManager()
					.getIssueObject(crqIssueKey);
			//Once Listner get Fired Then It will get Child Issue Status
			log.warn("************** checkTransitionStatus Befor Sleeping **************");
			//Problem occured because Listner is not fully executed before the below link checking code is executed to avoid that
			//its put into sleep.
			Thread.sleep(1000);
			log.warn("************** checkTransitionStatus Thread is Sleeping **************");
			LinkCollection linkCollection = issueLinkManager.getLinkCollection(
					mutableIssue.getGenericValue(), listenerView
							.getRemoteUser());
			for (Issue linkIssue : (Collection<Issue>) linkCollection
					.getAllIssues()) {
				log.warn("Inside For Loop Linked issue Id Is"
						+ linkIssue.getKey());
				if ("Task Closed".equals(linkIssue.getStatusObject().getName())
						|| "Task Cancelled".equals(linkIssue.getStatusObject()
								.getName())
						|| "Closed".equals(linkIssue.getStatusObject()
								.getName())
						|| "Cancelled".equals(linkIssue.getStatusObject()
								.getName())) {
					if ("Task Closed".equals(linkIssue.getStatusObject()
							.getName())
							|| "Closed".equals(linkIssue.getStatusObject()
									.getName())) {
						log.warn("checkIssueStatus closedStatusIssues"
								+ closedStatusIssues);
						closedStatusIssues++;
					} else {
						log.warn("checkIssueStatus cancelledStatusIssues"
								+ cancelledStatusIssues);
						cancelledStatusIssues++;
					}
				} else {
					isAnyNonClosedAndNonCancelledStatus = true;
				}

			}
			if (isAnyNonClosedAndNonCancelledStatus == false) {
				if (closedStatusIssues > 0) {
					// change the parent issue status to resolved
					targetTransitionName = RESOURCEBUNDLE.transitonResolve;
				} else if (cancelledStatusIssues > 0) {
					// change the parent issue status to cancelled
					targetTransitionName = RESOURCEBUNDLE.transitionCancel;
				}
			}

			log.warn("$$$$$$$$$$$ isAnyNonClosedAndNonCancelledStatus ===> "
					+ isAnyNonClosedAndNonCancelledStatus);
			log.warn("$$$$$$$$$$$ closedStatusIssues ===> "
					+ closedStatusIssues);
			log.warn("$$$$$$$$$$$ cancelledStatusIssues ===> "
					+ cancelledStatusIssues);
			log.warn("$$$$$$$$$$$ targetTransitionName ===> "
					+ targetTransitionName);
			if (targetTransitionName != null) {
				this.progressWorkflow(crqIssueKey, targetTransitionName);
			}
		} catch (InterruptedException e) {
			log.error("InterruptedException...", e);
		}
	}

}
*/